{% extends '__base_local__.html' %}

{% block title %}v2ray{% endblock %}
{% block beforehead %}
<style>
    html,
    body {
        scroll-behavior: smooth;
    }

    .v-enter-active,
    .v-leave-active {
        transition: opacity 1.5s ease;
        transition: translate 1.5s ease;
    }

    .fade-enter-from,
    .fade-leave-to {
        transition: translateY(0)
    }

    .slide-fade-enter-active {
        transition: all .3s ease-out;
    }

    .slide-fade-leave-active {
        transition: all .8s cubic-bezier(1.0, 0.5, 0.8, 1.0);
    }

    .slide-fade-enter-from,
    .slide-fade-leave-to {
        transform: translateY(0px);
        opacity: 0;
    }

    .tools-main {
        position: fixed;
        left: 95vw;
        bottom: 15vh;
        font-size: 1em;
        cursor: pointer;
    }

    .toast-main {
        position: fixed;
        right: 5vw;
        bottom: 15vh;
        font-size: 1em;
        cursor: pointer;
    }
</style>
{% endblock %}
{% block content %}

<!-- Content Header (Page header) -->

<section class="content-header">
    <h1>
        Blog
        <small>Blog panel</small>
    </h1>
    <ol class="breadcrumb">
        <li><a href="/"><i class="fa fa-dashboard"></i> Home</a></li>
        <li class="active">Blog</li>
    </ol>
</section>

<div class="container" id="main">
    <router-view></router-view>
</div>

{% endblock %}

{% block beforebody %}
<script src="static/vue/vue.global-3.2.31.js"></script>
<script src="static/vue/vuex.global-4.0.2.js"></script>
<script src="static/vue/vue-router.global-4.0.14.js"></script>
<script src="static/vue/vue3-sfc-loader-5.3.5.js"></script>
<script src="static/main.js"></script>
<script>

    const index = {
        components: {
            'loading': component('static/vue/loading.vue'),
            'list_item': component('static/vue/list_item.vue'),
            'export': component('static/vue/export.vue'),
            'import': component('static/vue/import.vue'),
            'navtb': component('static/vue/navtb.vue'),
        },
        template: `
            <div class="btn-toolbar" role="toolbar" aria-label="Toolbar with button groups">
                <div class="btn-group mr-2" role="group" aria-label="First group">
                    <a class="btn" role="button" @click="vue_import.show=true">导入</a>
                </div>
            </div>
            <list_item :fields="fields" :items="items" @select='select' @sort="sort"></list_item>
            <div id="liveToast" class="toast hide toast-main" role="alert" aria-live="assertive" aria-atomic="true" data-delay="2000" data-animation="true">
                <div class="toast-header">
                    <strong class="mr-auto">已复制</strong>
                    <button type="button" class="ml-2 mb-1 close" data-dismiss="toast" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
            </div>
            <transition>
                <loading v-if="loading"></loading>
            </transition>
            <export :show='vue_export.show' :content='vue_export.content' @hide="vue_export.show=false"></export>
            <import :show='vue_import.show' :content='vue_import.content' @hide="vue_import.show=false" @save="onImportClip"></import>
            <transition name="slide-fade">
                <div class="tools-main">
                    <button class="btn btn-sm d-block tools" v-if="selectItems.length >= 1" @click="deleteItems" data-toggle="tooltip" data-placement="top" title="删除">删除</button>
                    <button class="btn btn-sm d-block tools" v-if="selectItems.length >= 1" @click="export2" data-toggle="tooltip" data-placement="top" title="导出配置文件">导出</button>
                    <navtb></navtb>
                </div>
            </transition>
        `,
        data() {
            return {
                page: { 'total': 36, 'pages': 3, 'index': 1, 'size': 12 },
                items: [
                    {
                        name: '协议',
                        status: '订阅',
                        updated_at: '地址',
                    }
                ],
                loading: false,
                fields: [
                    {
                        name: 'name',
                        text: '名称',
                        order: 0,
                    },
                    {
                        name: 'status',
                        text: '状态',
                        order: 0,
                        listId: {
                            '2': '审核',
                            '3': '公开'
                        }
                    },
                    {
                        name: 'updated_at',
                        text: '修改时间',
                        order: 0,
                    },
                ],
                selectItems: [],
                vue_export: {
                    show: false,
                    content: ''
                },
                vue_import: {
                    show: false,
                    content: ''
                }
            }
        },
        mounted() {
            this.load()

        },
        computed: {
        },
        watch: {
            items: {
                handler(newVal, oldVal) {
                    // log(newVal)
                },
                deep: true,
            }
        },
        methods: {
            bload() {
                if (!this.loading) {
                    this.loading = true
                }
            },
            load() {
                this.loading = true
                get('blog/items', {}, {
                    _success: (data) => { this.items = data['msg']['items']; },
                    _final: () => { this.loading = false },
                    _before: () => { this.bload() }
                })
            },
            deleteItems() {
                log(this.selectItems)
                if (this.selectItems.length <= 0) return
                let ids = []
                this.selectItems.forEach(el => {
                    ids.push(el.id)
                })
                log(ids, 'deleteItems')
                let info = '[' + this.selectItems[0].name + ']'
                if (this.selectItems.length >= 2) {
                    info += ", [" + this.selectItems[1].name + "]...等" + this.selectItems.length + '项'
                }
                if (confirm('删除' + info + '?')) {
                    this.loading = true
                    post('blog/delete', {
                        ids: ids
                    }, {
                        _success: (data) => { this.items = data['msg']['items']; },
                        _final: () => { this.loading = false },
                        _before: () => { this.bload() }
                    })
                }
            },
            select(items) {
                this.selectItems = []
                for (let id of items) {
                    for (let item of this.items) {
                        if (item.id === id) {
                            this.selectItems.push(item)
                            break
                        }
                    }
                }
                if (this.selectItems.length === 1) {
                    this.enable = this.selectItems[0].enabled
                }
            },
            export2() {
                log(this.selectItems)
                if (this.selectItems.length <= 0) return
                let ids = []
                this.selectItems.forEach(item => {
                    ids.push(item['id'])
                })
                post('blog/export', { ids: ids }, {
                    _success: (data) => { this.vue_export.content = JSON.stringify(data['msg']['items'], null, "\t"); this.vue_export.show = true },
                    _final: () => { this.loading = false },
                    _before: () => { this.bload() }
                })
            },
            sort(field) {
                if (field['order'] === 1) {
                    field['order'] = -1
                } else if (field['order'] === -1) {
                    field['order'] = 1
                } else {
                    field['order'] = 1
                }
                for (let field_ of this.fields) {
                    if (field_['name'] === field['name']) {
                        field_['order'] = field['order']
                    } else {
                        field_['order'] = 0
                    }
                }
                this.items.sort((a, b) => {
                    let name = field['name']
                    if (!a[name] || !b[name]) {
                        if (field['order'] >= 0) {
                            if (!a[name] && b[name]) return -1
                            if (a[name] && !b[name]) return 1
                        } else {
                            if (!a[name] && b[name]) return 1
                            if (a[name] && !b[name]) return -1
                        }
                        if (!a[name] && !b[name]) return 0
                    }
                    if (typeof (a[name]) === 'number') {
                        if (field['order'] >= 0) {
                            return a[name] - b[name]
                        } else {
                            return b[name] - a[name]
                        }
                    }
                    else {
                        if (field['order'] >= 0) {
                            return a[name].localeCompare(b[name])
                        } else {
                            return b[name].localeCompare(a[name])
                        }
                    }
                })
            },
            onImportClip(content) {
                let objs = []
                try {
                    objs = JSON.parse(content)
                } catch (error) {
                    alert(error.message)
                    return
                }
                if (!(objs instanceof Array)) return
                objs.reverse()
                let items = []
                axios.post('blog/save', {
                    items: objs
                })
                    .then(
                        response => {
                            // console.log(response);
                            if (response.status === 200) {
                                let data = response.data
                                if (data['code'] === 0) {
                                    console.log('SUCCESS: ' + data['msg'])
                                    this.load()
                                    this.vue_import.show = false
                                } else {
                                    console.log('FAILED: ' + data['msg'])
                                }
                            }
                        })
                    .catch(function (error) {
                        console.log(error);
                    });
            },
        }
    }


    const routes = [
        {
            path: '/',
            name: 'index',
            component: index,
        },
    ]

    const router = VueRouter.createRouter({
        // 4. 内部提供了 history 模式的实现。为了简单起见，我们在这里使用 hash 模式。
        history: VueRouter.createWebHashHistory(),
        routes, // `routes: routes` 的缩写
    })


    const app = Vue.createApp({})
    // const app = Vue.createApp(index);
    //整个应用支持路由。
    app.use(router)
    // mount方法返回根组件实例
    app.mount('#main');

</script>
{% endblock %}